package cn.mugutu.finance.controller;

import cn.mugutu.finance.annotation.SysLog;
import cn.mugutu.finance.annotation.SysResource;
import cn.mugutu.finance.domain.system.Department;
import cn.mugutu.finance.dto.BaseResult;
import cn.mugutu.finance.dto.DepartmentDto;
import cn.mugutu.finance.dto.EasyUIResult;
import cn.mugutu.finance.exception.BusinessException;
import cn.mugutu.finance.query.DepartmentQuery;
import cn.mugutu.finance.service.system.DepartmentService;
import cn.mugutu.finance.utils.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/department")
public class DepartmentController extends BaseController {

    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/listUI")
    @SysResource(name = "部门管理", code = "department:listui")
    public String listUI() {
        return "department/list";
    }

    @RequestMapping("/list")
    @ResponseBody
    public EasyUIResult<DepartmentDto> list(DepartmentQuery query, int page, int rows) {
        setEasyUIParamsInQuery(query, page, rows);
        Pager<Department> pager = departmentService.findByPage(query);
        List<DepartmentDto> dtoList = DepartmentDto.departmentListToDepartmentDtoList(pager.getRows());
        return new EasyUIResult<DepartmentDto>(pager.getTotalCount(), dtoList);
    }

    /**
     * 查询所有部门
     * @return
     */
    @RequestMapping("/all")
    @ResponseBody
    public List<DepartmentDto> all() {
        List<Department> all = departmentService.findAll();
        List<DepartmentDto> dtolist = DepartmentDto.departmentListToDepartmentDtoList(all);
        return dtolist;
    }

    @RequestMapping("/get")
    @ResponseBody
    public Department getById(Long id) {
        return departmentService.get(id);
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @SysLog(description = "新增/修改部门")
    public BaseResult saveOrUpdate(Department department) {
        return departmentService.saveOrUpdateDepartment(department);
    }

    @RequestMapping("/delete")
    @ResponseBody
    @SysLog(description = "删除部门")
    public BaseResult delete(Long id) {
        try {
            departmentService.delete(id);
            return new BaseResult(true, "删除成功");
        } catch (Exception e) {
            throw new BusinessException("删除失败,请检查该部门下面是否有下级部门,或者联系系统管理员处理." + e.getMessage());
        }
    }
}
